import React, { Component } from 'react';
import { connect } from 'react-redux'
import { List, Stepper, Button, Dialog } from 'antd-mobile'
import { actionAddCar, actionSubCar, actionDeleteCar, actionSwitchOne } from '../../../store/actions'
class Index extends Component {
	// 处理 + - 功能
	handleChange(value, v) {
		if (value > v.count) {
			this.props.dispatch(actionAddCar(v))
		} else {
			this.props.dispatch(actionSubCar(v))
		}
	}
	// 处理删除
	handleDelete(v) {
		// 确认框
		Dialog.confirm({
			content: '确认要删除吗？',
			// 点击确定
			onConfirm: () => {
				this.props.dispatch(actionDeleteCar(v))
			}
		})
	}
	// 处理切换单选
	handleSwitchOne(v) {
		this.props.dispatch(actionSwitchOne(v))
	}
	render() {
		const { car } = this.props
		return (
			<div>
				<List>
					{
						car.map(v => {
							return <List.Item key={v.id}
								prefix={
									<div>
										{/* 受控组件 */}
										<input type="checkbox" checked={v.isChecked} onChange={ () => this.handleSwitchOne(v) } />
										<img src={v.url} alt="" />
									</div>
								}
								description={v.desc}
							>
								<p>	{v.title}</p>
								<div>
									<b style={{ color: 'red' }}>￥{v.price}</b>
									<Button color="danger" onClick={ () => this.handleDelete(v) }>删除</Button>
									{/* 受控组件 */}
									<Stepper value={v.count} onChange={(value) => this.handleChange(value, v)} min={1}></Stepper>
								</div>
							</List.Item>
						})
					}
				</List>
				<h1>
					全选<input type="checkbox" />
					{/* 总价： 循环遍历每一个数据，当数据字段isChecked 为真  累加单价 * 数量 */}
					<b>总价： { car.reduce((p, n) => n.isChecked ? p + n.price * n.count : p, 0) }</b>
				</h1>
			</div>
		);
	}
}

export default connect(state => state, dispatch => ({ dispatch }))(Index);
